//
//  FriendViewController.m
//  SportsSocial
//
//  Created by yull on 14/10/29.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "FriendViewController.h"
#import "FriendAddViewController.h"

#import "FriendCell.h"
#import "FriendNet.h"
#import "ChatViewController.h"
#import "PrivateMsgSender.h"
#import "GroupNet.h"

@interface FriendViewController () <UITableViewDataSource,UITableViewDelegate,FriendCellDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) UITableView *tableViewFriend;

@property (nonatomic, strong) NSMutableArray *arrayFriend;

@property (nonatomic, strong) UserModel *selectedUser;

@end

@implementation FriendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavibar];
    
    [self addCommonBackButton];
    
    self.tableViewFriend = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height-Navibar_Height) style:UITableViewStylePlain];
    self.tableViewFriend.delegate = self;
    self.tableViewFriend.dataSource = self;
    self.tableViewFriend.backgroundColor = [UIColor clearColor];
    self.tableViewFriend.separatorInset = UIEdgeInsetsZero;
    [self.view addSubview:self.tableViewFriend];
    
    self.tableViewFriend.tableFooterView = [[UIView alloc] init];
    
    [self getFriendList];
}

- (void)initNavibar
{
    self.navigationItem.title = @"我的好友";
    
    if (!self.fromAddAction) {
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame = CGRectMake(0, 0, 28, 26);
        [rightButton setImage:[UIImage imageNamed:@"title_icon4"] forState:UIControlStateNormal];
        [rightButton setImage:[UIImage imageNamed:@"title_icon4_selection"] forState:UIControlStateHighlighted];
        [rightButton addTarget:self action:@selector(addFriendClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
        
        self.navigationItem.rightBarButtonItem = rightItem;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrayFriend.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [FriendCell friendCellDefaultHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *friendIdentifier = @"FriendCell";
    FriendCell *friendCell = [tableView dequeueReusableCellWithIdentifier:friendIdentifier];
    if (!friendCell) {
        friendCell = [[FriendCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:friendIdentifier];
        friendCell.delegate = self;
    }
    [friendCell drawCellWithFriendInfo:[self.arrayFriend objectAtIndex:indexPath.row]];
    
    return friendCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.fromAddAction) {
        UserModel *friendModel = [self.arrayFriend objectAtIndex:indexPath.row];
        self.selectedUser = friendModel;
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"邀请" message:friendModel.name delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        [alertView show];
        
        return;
    }
    
    if (self.arrayFriend.count > 0) {
        UserModel *friendModel = [self.arrayFriend objectAtIndex:indexPath.row];
        ChatViewController *chatViewController = [[ChatViewController alloc] init];
        chatViewController.msgSender = [[PrivateMsgSender alloc] initWithUser:friendModel];
        chatViewController.navigationItem.title = friendModel.name;
        [self.navigationController pushViewController:chatViewController animated:YES];
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UserModel *friend = [self.arrayFriend objectAtIndex:indexPath.row];
    
    [self deleteFriendWithFriendModel:friend];
}

#pragma mark - FriendCellDelegate
- (void)onClickHeadImageViewWithFriendInfo:(UserModel *)friendInfo
{
    UIViewController *infoViewController = [Interface createUserInfoViewControllerWithUserId:friendInfo.userId userName:friendInfo.name];
    [self.navigationController pushViewController:infoViewController animated:YES];
}

#pragma mark - 网络
- (void)getFriendList
{
    [self showHUD];
    
    [FriendNet getFriendListWithSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hideHUD];
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSArray *dictArray = [responseObject objectForKey:@"data"];
            
            if (dictArray.count > 0) {
                if (!self.arrayFriend) {
                    self.arrayFriend = [NSMutableArray array];
                }
                
                for (NSDictionary *dict in dictArray) {
                    
                    UserModel *userModel = [UserModel userWithDict:dict];
                    if (!self.fromAddAction || ![[CurrentUser shareInstance] isGroup:self.groupId containUser:userModel.userId]) {
                        [self.arrayFriend addObject:userModel];
                    }
                }
                
                [self.tableViewFriend reloadData];
            }
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self hideHUD];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)deleteFriendWithFriendModel:(UserModel *)friendModel
{
    [FriendNet deleteFriendWithFriendId:friendModel.userId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSInteger row = [self.arrayFriend indexOfObject:friendModel];
            
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
            
            [self.arrayFriend removeObjectAtIndex:row];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"user_is_deleted" object:nil userInfo:@{@"userid":@(friendModel.userId)}];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableViewFriend deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        
        [self showHUD];
        
        [GroupNet inviteUser:self.selectedUser.userId toGroup:self.groupId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            [self hideHUD];
            
            BOOL success = [[responseObject objectForKey:@"success"] boolValue];
            if (success) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:@"发送邀请成功！" time:2];
                });
            } else {
                NSString *message = [responseObject objectForKey:@"message"];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self showText:message time:2];
                });
            }
        } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        
            [self hideHUD];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"网络连接失败" time:2];
            });
        }];
    }
}

- (void)dealloc
{
    self.tableViewFriend.delegate = nil;
    self.tableViewFriend.dataSource = nil;
}

#pragma mark - Action
- (void)addFriendClick:(id)sender
{
    FriendAddViewController *addViewController = [[FriendAddViewController alloc] init];
    [self.navigationController pushViewController:addViewController animated:YES];
}
@end
